Estadística y Manejo de Datos con R (EMDR) — Virtual
ggplot2ggplot2ggplot2 es un paquete de R para realizar gráficos modernos de alta calidad.
Utiliza una dinámica distinta a los gráficos básicos de R.
Es sintético: permite elaborar gráficos complejos con código sencillo.
Los Marcos de Datos son la estructura básica de ggplot2
Gráficos ¿más bonitos?
ggplot2ggplot2The Economistggplot2ggplot2ggplot() recibe un data frame (marco de datos).
aes() recibe los componentes a graficar, junto con la variable agrupadora.
geom() especifica la capa que determina el tipo de gráfico.
ggplot2ggplot2 debe estar instalado y cargado.install.packages("ggplot2")
library(ggplot2)
geom_point()Orange?Orange
head(Orange)
## Tree age circumference ## 1 1 118 30 ## 2 1 484 58 ## 3 1 664 87 ## 4 1 1004 115 ## 5 1 1231 120 ## 6 1 1372 142
geom_point()ggplot(Orange, aes(x = age, y = circumference)) + geom_point()
geom_point()ggplot(Orange, aes(x = age, y = circumference, color = Tree)) + geom_point(shape = 1, size = 4)
geom_point()ggplot(Orange, aes(x = age, y = circumference, color = Tree)) + geom_point(shape = 1) + geom_smooth(method = lm, se = FALSE)
## `geom_smooth()` using formula 'y ~ x'
geom_point()ggplot(Orange, aes(x = age, y = circumference, shape = Tree)) + geom_point(size = 2)
geom_point()ggplot(Orange, aes(x = age, y = circumference, shape = Tree)) + geom_point() + scale_shape_manual(values = c(1:5))
geom_line()ToothGrowth. Mantengamos en mente para el siguiente Tema, la codificación de la función std.library(dplyr)
library(magrittr)
?ToothGrowth
head(ToothGrowth)
std <- function(x){sd(x)/ sqrt(length(x))}
TG <- ToothGrowth %>%
group_by(dose, supp) %>%
summarize(ml = mean(len), sle = std(len))
## len supp dose ## 1 4.2 VC 0.5 ## 2 11.5 VC 0.5 ## 3 7.3 VC 0.5 ## 4 5.8 VC 0.5 ## 5 6.4 VC 0.5 ## 6 10.0 VC 0.5
geom_line()ggplot(TG, aes(x = dose, y = ml, group = supp)) + geom_line()
geom_line()ggplot(data = TG, aes(x = dose, y = ml, group = supp, color = supp)) + geom_line() + geom_point()
geom_line()ggplot(data = TG, aes(x = dose, y = ml, group = supp, color = supp)) + geom_line() + geom_point() + geom_errorbar(aes(ymax = ml + sle, ymin = ml - sle), width = 0)
geom_line()ggplot(data = TG, aes(x = dose, y = ml, group = supp, color = supp)) +
geom_line() + geom_errorbar(aes(ymax = ml+sle, ymin = ml-sle), width = 0) +
xlab("Dose (ml)") + ylab("Length (mm)") + ggtitle("Length vs Dose")
geom_bar()PlantGrowth.library(dplyr) library(magrittr) ?PlantGrowth head(PlantGrowth) mPG <- PlantGrowth %>% group_by(group) %>% summarize(mw = mean(weight), sdw = sd(weight))
## weight group ## 1 4.17 ctrl ## 2 5.58 ctrl ## 3 5.18 ctrl ## 4 6.11 ctrl ## 5 4.50 ctrl ## 6 4.61 ctrl
geom_bar()ggplot(mPG, aes(x= group, y= mw)) + geom_bar(stat = "identity")
geom_bar()ggplot(data = mPG, aes(x = group, y = mw, fill = group)) + geom_bar(stat = "identity", color = "black") + geom_errorbar(aes(ymax = mw + sdw, ymin = mw - sdw), width = 0.25)
geom_histogram()Seatbelts.?Seatbelts
SB.df <- as.data.frame(Seatbelts) head(SB.df)
## DriversKilled drivers front rear kms PetrolPrice VanKilled law ## 1 107 1687 867 269 9059 0.1029718 12 0 ## 2 97 1508 825 265 7685 0.1023630 6 0 ## 3 102 1507 806 319 9963 0.1020625 12 0 ## 4 87 1385 814 407 10955 0.1008733 8 0 ## 5 119 1632 991 454 11823 0.1010197 10 0 ## 6 106 1511 945 427 12391 0.1005812 13 0
geom_histogram()ggplot(SB.df, aes(x = DriversKilled)) + geom_histogram(binwidth = 10, color = "black", fill = "white")
geom_histogram()ggplot(SB.df, aes(x = DriversKilled, fill = as.factor(law))) + geom_histogram(binwidth = 10, alpha =.5, position = "identity")
OrchardSprays.?OrchardSprays
head(OrchardSprays)
p <- ggplot(data = OrchardSprays, aes(x = factor(treatment), y = rowpos)) +
geom_point(aes(color = decrease), size = 16, shape = 15)
scale_color_gradient()p <- p + scale_color_gradient(low = "red", high = "yellow", "Efecto",
with(OrchardSprays, c(min(decrease), mean(decrease),
max(decrease))), labels = c("Alto","Medio","Bajo"))
p
bp <- ggplot(data = PlantGrowth, aes(x = group, y = weight, fill = group)) + geom_boxplot() + theme_bw()
bp <- bp + ggtitle("Plant growth")
bp <- bp + ggtitle("Plant growth with \n different treatments")
bp + xlab("Group") + ylab("Weight") +
scale_x_discrete(labels =
c("ctrl" = "Control","trt1" = "Treatment1","trt2" = "Treatment2"))
bp + scale_fill_brewer(name ="Experimental\nCondition", palette = "Greens")
facet_griddata(tips, package="reshape2") sp <- ggplot(tips, aes(x= total_bill, y= tip/total_bill)) + geom_point(shape = 1)
facet_gridsex (horizontal)sp + facet_grid(sex ~ .)
facet_gridsex (vertical).sp + facet_grid(. ~ sex)
facet_gridsex y day.sp + facet_grid(sex ~ day)
facet_wrapsp + facet_wrap(~ day, ncol = 2) # intenta 3 y 5
ggsave.ggsave(file ="myplot.pdf") ggsave(file ="myplot.png") # Soporte png ggsave(myplot, file ="myplot.pdf") # Usando el objeto ggsave(myplot, file ="myplot.pdf", width = 4, height = 4) # Especificando el tamaño
diamonds.?diamonds head(diamonds)
library(plotly) plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
# Resultado interactivo, mueve el cursor sobre el gráfico.
library(lattice) xyplot(lat ~ long | cut(depth, 2), data = quakes, outer = T, grid = T)
library(lattice) heatmap(matrix(DNase$density, ncol = 11))
library(leaflet) leaflet() %>% addTiles() %>% # Add default OpenStreetMap map tiles addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
# Resultado interactivo, mueve el cursor sobre el gráfico.
library(networkD3)
src <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
networkData <- data.frame(src, target)
simpleNetwork(networkData) # Resultado interactivo, mueve el cursor sobre el gráfico.
Energy <- jsonlite::fromJSON("energy.json")
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
Target = "target", Value = "value", NodeID = "name", units = "TWh",
fontSize = 12, nodeWidth = 30)
# Resultado interactivo, mueve el cursor sobre el gráfico.
ggplot2?
Estadística y Manejo de Datos con R (EMDR) por
Marcos F. Rosetti S. y Luis Pacheco-Cobos se distribuye bajo una Licencia Creative Commons Atribución 4.0 Internacional.